<template>
<view class="pageconfig">
<!-- 顶部说明文本 -->
<view class="description">
<text class="description-text">这是顶部的说明文本</text>
</view>
<!-- 顶部区域 -->
<view class="flex-container top-bar">
<view class="flex-item top-item blue-bg">
<view class="button-content">
<text class="text3">地区</text>
<text class="text4" v-if="showRegion">{{ currentRegion }}</text>
</view>
</view>
<view class="flex-item top-item blue-bg">
<view class="button-content">
<text class="text6">机器人数量</text>
<text class="text7">在线{{ onlineCount }}/离线{{ offlineCount }}</text>
</view>
</view>
<view class="flex-item top-item blue-bg">
<text class="text9">编号</text>
<view class="input10 cu-form-group">
<input type="text" class="text-left" placeholder="" v-model="souid" />
</view>
</view>
</view>
<!-- 动态生成编号状态块 -->
<view v-for="item in filteredItems" :key="item.id" class="flex-container item-container">
  <view class="flex-item status" :class="{ online: item.status === 'online', offline: item.status === 'offline' }" @click="toggleIP(item)">
    <text class="text13">{{ item.idStatusDisplay }}</text>
  </view>
  <view>
<button @tap="goToAutoPage(item.id)" class="button-style">
<view class="button-content">
<text class="text16">配置按钮</text>
</view>
</button>
</view>
</view>
<view class="jsonmsg-display">
<text>jsonmsg: {{ jsonString }}</text>
</view>
</view>
</template>

<script>
import { mapState } from 'vuex'; 
let updateTimeout;
export default {
  data() {
    return {
      udpClient: null,
	      updateTimeout: null,  // 状态显示延迟更新的定时器
	      offlineTimers: {},    // 用于存储每个设备的离线定时器
	      globalOfflineTimer: null, // 全局离线判断定时器
      address: '',
      jsonmsgContent: '', 
	  jsonString: '', 
      onlineCount: 0,
      offlineCount: 0,
      socketPort: 9091,
	  showIP: false, 
      ids: [1, 2, 3, 6],
      statusData: ['offline', 'offline', 'offline', 'offline'],
      searchCounts: {},
      items: [],
      souid: '',
	  mode: 1,
	  ip: null,
	  id: null,
    };
  },
  computed: {
    ...mapState({
      udpMessages: state => state.udpMessages, // 从 Vuex 中获取 udpMessages
    }),
    filteredItems() {
      if (!this.souid.trim()) {
        return this.items;
      }
      const searchID = parseInt(this.souid, 10);
      if (!isNaN(searchID)) {
        return this.items.filter(item => item.id === searchID);
      }
      const region = this.souid.trim().toLowerCase();
      const [start, end] = this.getIDRangeByRegion(region);
      return this.items.filter(item => item.id >= start && item.id < end);
    },
    currentRegion() {
      if (!this.souid.trim()) {
        return this.regionDeviceCountsString;
      }
      const searchID = parseInt(this.souid, 10);
      if (!isNaN(searchID) && this.ids.includes(searchID)) {
        return this.getRegionByID(searchID).toUpperCase();
      }
      return '';
    },
    showRegion() {
      if (!this.souid.trim()) {
        return true;
      }
      const searchID = parseInt(this.souid, 10);
      return !isNaN(searchID) && this.ids.includes(searchID);
    },
    regionDeviceCounts() {
      const counts = {};
      this.ids.forEach(id => {
        const region = this.getRegionByID(id).toUpperCase();
        if (!counts[region]) {
          counts[region] = 0;
        }
        counts[region]++;
      });
      return counts;
    },
    regionDeviceCountsString() {
      return Object.entries(this.regionDeviceCounts)
        .map(([region, count]) => `${region}${count}`)
        .join('');
    },
	    udpLogs() {
	        // 获取全局的UDP日志
	        return getApp().globalData.udpLogs || [];
	    }
  },
  watch: {
	      udpLogs(newLogs) {
	          // 当日志变化时，自动更新页面提示
	          if (newLogs.length > 0) {
	              this.showLogTip(newLogs);
	          }
	      },
    udpMessages: {
      handler(newMessages) {
        this.jsonmsgContent = newMessages.length ? newMessages[newMessages.length - 1] : '';
		this.processJsonMsg(); 
	  },
      deep: true,
      immediate: true, // 页面加载时立即执行一次 handler
    },
	jsonmsgContent: { // 新增对 jsonmsgContent 的监视
	    handler(newContent) {
	      if (newContent) {
	        this.processJsonMsg(); // 当 jsonmsgContent 变化时调用 processJsonMsg
	      }
	    },
	    immediate: true,
	  },
    souid: function(newID) {
      const searchID = parseInt(newID, 10);
      if (!isNaN(searchID)) {
        this.checkAndAddID(newID);
      } else {
        this.updateItems();
      }
    },
    basic: {
      handler(newBasic) {
        this.updateIDStatusDisplay();
        this.updateItems();
      },
      deep: true
    }
  },
  onLoad() {
	this.startUDPService();
    this.updateItems();
    this.jsonmsgContent = this.udpMessages.length ? this.udpMessages[this.udpMessages.length - 1] : '';
  },
  methods: {
	      showLogTip(logs) {
	          // 显示最新日志提示
	          uni.showToast({
	              title: 'UDP日志更新',
	              icon: 'none'
	          });
	      },
	  startUDPService() {
	          // 模拟后台运行逻辑，启动UDP
	          console.log('后台启动UDP服务');
	  
	          // 启动后台逻辑
	          //this.runUDPInBackground();
	      },
		//  runUDPInBackground() {
		          // 模拟后台逻辑处理，例如启动定时器模拟后台监听
		        //  setInterval(() => {
		              //console.log('UDP后台运行中...');
		              // 模拟记录日志信息，推送到主页面
		              //this.logUDPMessage('新的UDP消息');
		          //}, 1000); // 每5秒触发一次
		    //  },
			  logUDPMessage(message) {
			          // 处理日志，可以存储在全局变量或其他方式
			          getApp().globalData.udpLogs = getApp().globalData.udpLogs || [];
			          getApp().globalData.udpLogs.push(message);
			  
			          // 更新日志到页面显示
			          this.$emit('udp-log-update', message);
			      },
	    toggleIP(item) {
	      if (item.status === 'online') { // 仅当状态为在线时才允许点击
	        this.showIP = !this.showIP; // 切换显示状态
	        if (this.showIP) {
	          item.idStatusDisplay = this.ip; // 显示 IP
	        } else {
	          item.idStatusDisplay = `编号${item.id}状态显示在线`; // 恢复在线状态显示
	        }
	      }
	    },

	    async processJsonMsg() {
	      // 将 jsonmsgContent 转换为字符串
	      const jsonString = JSON.stringify(this.jsonmsgContent, null, 2);
	      const parsedContent = JSON.parse(jsonString); // 解析为对象
	    this.jsonString=jsonString;
	      // 新增检查 jsonString 是否为空对象
	      if (Object.keys(parsedContent).length === 0) {
	        this.statusData.fill('offline'); // 设置所有状态为离线
	        this.updateItems(); // 更新 items
	        return; // 退出函数
	      }
	      const index = this.ids.indexOf(1);
	      if (index !== -1) {
	        this.statusData[index] = 'online';
	      }
	    
	      this.updateItems(); // 更新 items
	      if (parsedContent.msg) {
	        const ip = parsedContent.address; 
	        this.ip = ip;
	        const msgContent = JSON.parse(parsedContent.msg); 
	    
	        // 新增检查 msgContent 和 basic 是否存在
	        if (msgContent && msgContent.basic) {
	          const msgbasic = msgContent.basic; 
	          const ID = msgbasic.ID; 
	          this.id = ID; // 使用 ID
	          const mode = msgbasic.mode; 
	          this.mode = mode;
	    
	          // 更新 statusData
	          const index = this.ids.indexOf(ID);
	          if (index !== -1) {
	            this.statusData[index] = 'online'; // 将对应 ID 的状态设为在线
	          }
	          this.updateItems(); // 更新 items
	        }
	      }
	    },


    updateOnlineOfflineCount(status) {
      if (status === 'online') {
        this.onlineCount++;
        this.offlineCount = Math.max(this.offlineCount - 1, 0);
      } else {
        this.offlineCount++;
        this.onlineCount = Math.max(this.onlineCount - 1, 0);
      }
    },
    
    
    updateStatusDisplay() {
            clearTimeout(this.updateTimeout);
            this.updateTimeout = setTimeout(() => {
                this.items.forEach(item => {
                    item.idStatusDisplay = `编号${item.id}状态显示${item.status === 'online' ? '在线' : '离线'}`;
                });
            }, 1000); // 500ms 延迟更新状态显示
        },
    
        updateItems() {
        // 清空在线和离线计数
        this.onlineCount = 0;
        this.offlineCount = 0;

        // 检查 `statusData` 和 `ids` 是否为非空数组
        if (!this.statusData || !this.ids || this.statusData.length !== this.ids.length) {
            console.error('Error: statusData or ids are not properly initialized or their lengths do not match.');
            return;  // 防止后续操作错误
        }

        // 更新 items 数组
        this.items = this.ids.map((id, index) => {
            const isOnline = this.statusData[index] === 'online'; // 使用索引来确保获取正确的数据
            
            if (isOnline) {
                // 如果设备在线，清除其离线定时器
                if (this.offlineTimers[id]) {
                    clearTimeout(this.offlineTimers[id]);
                    delete this.offlineTimers[id];
                }

                // 更新在线计数
                this.onlineCount++;
                return {
                    id,
                    status: 'online',
                    idStatusDisplay: `编号${id}状态显示在线`,
                };
            } else {
                // 如果设备当前为离线状态，暂时保持当前状态，设置2秒延迟定时器
                if (!this.offlineTimers[id]) {
                    this.offlineTimers[id] = setTimeout(() => {
                        const item = this.items.find(item => item.id === id);
                        if (item && this.statusData[this.ids.indexOf(id)] !== 'online') {
                            // 延迟到期后，如果仍未收到在线状态，将设备标记为离线
                            item.status = 'offline';
                            item.idStatusDisplay = `编号${item.id}状态显示离线`;
                            this.offlineCount++;
                            this.updateStatusDisplay(); // 更新状态显示
                        }
                        delete this.offlineTimers[id];
                    }, 2000); // 2秒延迟
                }

                // 返回当前状态
                const currentStatus = this.items.find(item => item.id === id)?.status || 'offline';
                if (currentStatus === 'offline') {
                    this.offlineCount++;
                }
                return {
                    id,
                    status: currentStatus,
                    idStatusDisplay: `编号${id}状态显示${currentStatus === 'online' ? '在线' : '离线'}`,
                };
            }
        });
    
            // 如果当前 statusData 为0，启动全局延迟定时器判断是否将所有状态设为离线
            if (this.statusData.length === 0) {
                if (!this.globalOfflineTimer) {
                    this.globalOfflineTimer = setTimeout(() => {
                        if (this.statusData.length === 0) {
                            // 如果2秒后 statusData 依然为0，则标记所有设备为离线
                            this.items.forEach(item => {
                                item.status = 'offline';
                                item.idStatusDisplay = `编号${item.id}状态显示离线`;
                            });
                            this.offlineCount = this.items.length; // 所有项都为离线
                            this.onlineCount = 0; // 在线计数为 0
                            this.updateStatusDisplay(); // 更新状态显示
                        }
                        clearTimeout(this.globalOfflineTimer);
                        this.globalOfflineTimer = null;
                    }, 2000); // 延迟2秒
                }
            } else {
                // 如果 statusData 不为0，清除全局定时器
                clearTimeout(this.globalOfflineTimer);
                this.globalOfflineTimer = null;
            }
    
            this.updateStatusDisplay(); // 调用更新状态显示函数
        },

    checkAndAddOrUpdateID(newID) {
      const id = parseInt(newID, 10);
      if (!isNaN(id)) {
        const index = this.ids.indexOf(id);
        if (index !== -1) {
          this.statusData[index] = 'online';
        } else {
          this.ids.push(id);
          this.statusData.push('online');
        }
        this.updateItems();
      }
    },
    checkAndAddID(newID) {
      const id = parseInt(newID, 10);
      if (!isNaN(id)) {
        if (!this.searchCounts[id]) {
          this.searchCounts[id] = 1;
        } else {
          this.searchCounts[id]++;
        }
        if (this.searchCounts[id] === 2 && !this.ids.includes(id)) {
          this.ids.push(id);
          this.statusData.push('offline');
          this.updateItems();
        } else if (this.searchCounts[id] === 3) {
          const index = this.ids.indexOf(id);
          if (index !== -1) {
            this.ids.splice(index, 1);
            this.statusData.splice(index, 1);
            this.updateItems();
          }
          delete this.searchCounts[id];
        }
      }
    },
    getRegionByID(id) {
      const regionIndex = Math.floor(id / 10);
      return String.fromCharCode(97 + regionIndex);
    },
    getIDRangeByRegion(region) {
      const regionIndex = region.toLowerCase().charCodeAt(0) - 97;
      const start = regionIndex * 10;
      const end = start + 10;
      return [start, end];
    },
    goToAutoPage11(id) {
      uni.navigateTo({ url: `/pages/index/auto?id=${id}` });
    },
	goToAutoPage(id) {
	  
	  // 检查是否有值或为空
	  if (id === null || id === undefined || id === '') {
	    uni.navigateTo({ url: `/pages/index/manual?id=${id}` }); // 跳转到手动页面
		
	  } else {
	    if (this.mode === 9) {
	      uni.navigateTo({ url: `/pages/index/auto?id=${id}` }); // 跳转到自动
	    } else {
	      uni.navigateTo({ url: `/pages/index/manual?id=${id}` }); // 跳转到其他页面
		  console.log('Navigating with ID:', this.mode); // 调试信息
	    }
	  }
	},
  },
  onUnload() {
    this.udpClient.release();
  }
}
</script>



<style lang="less">
.pageconfig {
  width: 100%;
  height: 100vh;
  overflow-y: scroll;
}

.description {
  width: 100%;
  padding: 10px;
  background-color: #f5f5f5;
  text-align: center;
}

.description-text {
  color: #333;
  font-size: 18px;
}

.flex-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  margin-bottom: 10px;
}

.flex-item {
  flex: 1;
  padding: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-size: 14px;
  margin: 5px;
  text-align: center;
  border-radius: 5px; /* 添加圆角 */
}

.top-item {
  height: 50px; /* 调整顶部区域高度 */
}

.blue-bg {
  background-color: blue; /* 顶部标签块背景色蓝色 */

}

.item-container {
  margin-bottom: 10px;
}

.flex-item.status {
  flex: 3;
  height: 30px; /* 减小高度 */
  transition: background-color 1s ease;
  &.online {
    background-color: green; /* 在线状态背景颜色 */
  }
  &.offline {
    background-color: red; /* 离线状态背景颜色 */
  }
}

.button-container {
  flex: 1;
  margin-right: 40px; /* 右边留点空间 */
}

.button-style {
  width: calc(100% - 10px); /* 调整按钮宽度，留出右边空间 */
  background-color: yellow; /* 配置按钮背景色黄色 */
  border: none;
  color: black;
  font-size: 14px;
  padding: 7px;
  cursor: pointer;
  text-align: center;
  border-radius: 8px; /* 添加圆角 */
}

.button-style:active {
  background-color: green; /* 配置按钮按下时背景色绿色 */
}

.button-content {
  width: 80px; /* 设置固定宽度 */
  height: 20px; /* 设置固定高度 */
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.input10 {
  width: 100%;
  background-color: #ffffff;
  margin: 10px 0;
  border-radius: 8px; /* 添加圆角 */
}

.text3, .text4, .text6, .text7, .text9, .text13, .text16 {
  margin: 5px 0;
}
</style>
